<template>
  <div class="OrgDepartment">
    <!-- 搜索 -->
    <AutoComplete
      class="search-input"
      v-model="nameOrCode"
      :data="searchResult"
      @on-search="remoteSearch"
      @on-select="selsectOrg"
      @on-clear="clearSearch"
      :placeholder="$t('module.orgManage.searchDept')"
      icon="md-search"
      clearable
    >
      <Option v-for="(option, index) in searchResult" :value="option" :key="index">{{ option }}</Option>
      <p class="complete-more get-complete-more" v-if="searchResult.length >= 10 && isShowMore" @click="showMore">
        {{ $t("common.showMore") }}
      </p>
    </AutoComplete>
    <div class="operate-wrapper">
      <!-- 部门 - 新建 -->
      <RPButton :text="$t('module.orgManage.newRootDept')" optType="save" @click="newDept('org', 'new')" />
      <!-- <CommonImportExport :configs="importExportConfigs"></CommonImportExport> -->
    </div>
    <!-- 表格 -->
    <div>
      <el-table
        lazy
        :data="tableData"
        style="width: 98%; margin: 0 auto;"
        row-key="orgId"
        :tree-props="{ children: 'childrenDept', hasChildren: 'hasChildren' }"
        :load="getChildrenDep"
      >
        <el-table-column prop="orgCode" :label="$t('module.orgManage.deptCode')"></el-table-column>
        <el-table-column prop="orgName" :label="$t('module.orgManage.deptName')"></el-table-column>
        <el-table-column prop="orderNo" :label="$t('module.orgManage.sortId')" width="120" align="center"></el-table-column>
        <el-table-column :label="$t('common.status')" width="120" align="center">
          <template slot-scope="scope">
            <StatusButton style="justify-content: center" :status="scope.row.enabled == 1 ? '0' : '1'">{{
              scope.row.enabled == 1 ? $t("common.enable") : $t("common.disable")
            }}</StatusButton>
          </template>
        </el-table-column>
        <el-table-column :label="$t('module.orgManage.operation')" width="120">
          <template slot-scope="scope">
            <RowTools :data="RowToolsData(scope)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import publicApi from "@/api/public.js";
import locales from "../locales.js";
import positionInfo from "./positionInfo.vue";
import NewDepartment from "./NewDepartment.vue";
import CommonImportExport from '@/components/import-and-export/index.vue'

export default {
  name: "orgDepartment",
  mixins: [locales],
  components: {
    CommonImportExport
  },
  props: {
    orgInfo: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      isShowMore: true,
      pageNum: 1,
      searchResult: [],
      tableData: [],
      nameOrCode: "",
      orgList: [],
      query: {
        orgPath: "",
        orgTypeFilter: 1,
        enabled: ""
      },
      defaultProps: {
        children: "childrenDept",
        label: "orgName"
      }
    };
  },

  created() {
    this.getDeptTreeList();
  },

  methods: {
    // 搜索结果大于10条，点击查看更多
    showMore() {
      this.getSelectNode(this.nameOrCode);
    },
    getSelectNode(value) {
      // 点击查看更多，pageNum改为2，从第二页开始查询
      this.pageNum++;
      if (value && value.indexOf("/") == -1) {
        let param = {
          condition: {
            parentOrgPath: this.orgInfo.orgPath,
            nameOrCode: value,
            orgTypeFilter: 2
          },
          pageNum: this.pageNum,
          pageSize: 10
        };
        publicApi
          .getListOrganizationPaths(param)
          .then(data => {
            if (data.records.length > 0) {
              this.loading = false;
              let pathArr = [];
              let orgArr = [];
              const list = data.records.map(item => {
                pathArr.push(item.orgNameFullPath);
              });

              orgArr = data.records;

              this.$nextTick(() => {
                this.searchResult = this.searchResult.concat(pathArr);
                this.orgList = this.orgList.concat(orgArr);
              });
            } else {
              // 查询结果，data.records为空数组时，隐藏查看更多按钮
              this.isShowMore = false;
            }
          })
          .catch(err => {
            this.loading = false;
          });
      }
    },
    // 选择搜索到的组织路径
    selsectOrg(value) {
      let data = this.orgList.filter(item => {
        if (item.orgNameFullPath == value) {
          return item.orgId;
        }
      });
      publicApi
        .getTreeBySelectOrg({ parentOrgPath: this.orgInfo.orgPath, orgId: data[0].orgId, orgTypeFilter: 2 })
        .then(data => {
          let arrData = data.map(item => {
            delete item.hasChildren;
            return item;
          });
          this.tableData = arrData;
        })
        .catch(err => {});
    },
    debounce(fn, wait = 300) {
      if (this.fun !== null) {
        clearTimeout(this.fun);
      }
      this.fun = setTimeout(fn, wait);
    },
    // 根据组织树编码和名称搜索
    remoteSearch(value) {
      this.debounce(() => {
        this.getListOrganizationPaths(value);
      }, 300);
    },
    getListOrganizationPaths(value) {
      this.pageNum = 1; // 当重新搜索时，默认从第一页开始查询
      this.isShowMore = true; // 当重新搜索时，默认显示查看更多
      this.searchResult = []; //数组中只包含orgNameFullPath
      this.orgList = []; // 数组中包含orgId orgNameFullPath orgName orgPath
      let param = {
        condition: {
          parentOrgPath: this.orgInfo.orgPath,
          nameOrCode: value,
          orgTypeFilter: 2
        },
        pageNum: this.pageNum,
        pageSize: 10
      };
      if (value !== "") {
        this.loading = true;
        publicApi
          .getListOrganizationPaths(param)
          .then(data => {
            this.loading = false;
            data.records.map(item => {
              this.searchResult.push(item.orgNameFullPath);
            });

            this.orgList = data.records;
          })
          .catch(err => {
            this.loading = false;
          });
      } else {
        this.orgList = [];
      }
    },
    // 点击清空按钮
    clearSearch() {
      this.searchResult = [];
      this.nameOrCode = "";
      this.getDeptTreeList();
    },
    // 获取部门树列表
    getDeptTreeList() {
      this.tableData = [];
      let orgInfo = {
        orgPath: this.orgInfo.orgPath,
        orgTypeFilter: 2,
        enabled: ""
      };
      publicApi.queryOrg(orgInfo).then(response => {
        let data = response || [];
        let arrData = data.map(item => {
          item.hasChildren = true;
          return item;
        });
        this.tableData = arrData;
      });
    },
    // 列表懒加载
    getChildrenDep(row, treeNode, resolve) {
      publicApi.queryOrg({ orgPath: row.orgPath, orgTypeFilter: 2, enabled: 1 }).then(children => {
        let arrData = children.map(item => {
          item.hasChildren = true;
          return item;
        });
        resolve(arrData);
      });
    },
    // 新建部门
    newDept(idx, newOrEdit, row) {
      if (!this.orgInfo.orgId) {
        this.$message.error({
          content: this.$t("module.orgManage.enterOrg"),
          duration: 3
        });
        return;
      }
      this.deptNodeData = row;
      // 父组织路径
      let parentOrgPath = row ? row.orgPath : this.orgInfo.orgPath;
      // idx:org代表是在组织下新建根部门节点，dept代表是在根部门下新建子部门节点
      //新建根部门：在组织下新建根部门，currentOrgId、parentId都为当前选中的组织树节点id
      //新建子部门：在根部门下新建子部门，currentOrgId为当前选中的组织树节点id、parentId为当前选中的根部门树节点id
      new this.$pageModal(
        NewDepartment,
        {
          props: {
            // tenantCode: "0000"
            orgInfo: {
              idx: idx,
              newOrEdit: newOrEdit,
              row: newOrEdit == "edit" ? row : {},
              tenantCode: this.tenantCode, //租户编码
              currentOrgId: this.orgInfo.orgId,
              orgPath: parentOrgPath,
              parentId: idx == "org" ? this.orgInfo.orgId : row.orgId
            }
          }
        },
        data => {
          if (data) {
            this.getDeptTreeList({ deptId: this.orgInfo.orgId });
            // if (data.newOrEdit == "new") {
            //   this.getDeptTreeList({ deptId: this.orgInfo.orgId });
            // } else if (data.newOrEdit == "edit") {
            //   this.getDeptTreeList({ deptId: this.orgInfo.orgId });
            // }
          }
        }
      );
    },
    // 表格操作列的icon
    RowToolsData(scope) {
      return [
        {
          type: "icon",
          icon: "md-create",
          text: this.$t("module.orgManage.editDept"),
          handle: () => {
            this.newDept("dept", "edit", scope.row);
          }
        },
        {
          type: "icon",
          icon: "md-add",
          text: this.$t("module.orgManage.newDept"),
          handle: () => {
            this.newDept("dept", "new", scope.row);
          }
        },
        {
          type: "icon",
          icon: "ios-person",
          text: this.$t("module.orgManage.positionAmanagement"),
          handle: () => {
            new this.$sidelipPage(positionInfo, {
              props: {
                departmentInfo: {
                  tenantCode: this.tenantCode, //租户编码
                  department: scope.row
                }
              }
            });
          }
        }
      ];
    }
  },
  watch: {
    nameOrCode: {
      handler(value) {
        if (!value) {
          this.clearSearch();
        }
      },
      deep: true
    },
    "orgInfo.orgPath": {
      handler(value) {
        this.nameOrCode = "";
        this.getDeptTreeList();
      },
      deep: true
    }
  },
  computed: {
    importExportConfigs() {
      const apiPrefix = window?.RPConfig?.mgt || ''
      const queryTemplateParams = {
        requestPath: `${apiPrefix}/template/list`,
        requestMethod: 'post',
        requestParams: {
          templateCategory: 'DEPARTMENT'
        }
      }
      return [
        {
          type: 'import',
          btnText: '导入',
          requestPath: `${apiPrefix}/department/importExcel`,
          successCallback: this.clearSearch
        },
        {
          type: 'export',
          btnText: '导出',
          requestPath: `${apiPrefix}/department/listExport`,
          requestMethod: 'get',
          requestParams: {
            orgPath: this?.orgInfo?.orgPath || '' // 父组织路径
          }
        },
        {
          type: 'export',
          exportType: 'downloadTemplate',
          btnText: '下载部门模板',
          requestPath: `${apiPrefix}/department/excelTemplateExport`,
          requestMethod: 'get',
          requestParams: {
            attributeTemplateId: ''
          },
          queryTemplateParams
        }
      ]
    }
  }
};
</script>

<style lang="less">
.OrgDepartment {
  .search-input {
    width: 300px;
    margin-left: 10px;
    margin-bottom: 5px;
  }
  .ivu-btn {
    display: block;
    background-color: #ff6f4b;
    border-color: #ff6f4b;
    &:hover {
      background-color: #ff6f4b;
      border-color: #ff6f4b;
    }
    margin-left: 10px;
    margin-bottom: 5px;
  }
  .el-table th {
    background-color: #f5f5f5;
  }
  .operate-wrapper {
    display: flex;
    .ivu-btn {
      margin-left: 0;
    }
  }
}
</style>
